package com.ramos.kuaixiao.ui;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.githang.statusbar.StatusBarCompat;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.ramos.kuaixiao.App;
import com.ramos.kuaixiao.R;
import com.ramos.kuaixiao.adapter.WareAdapter;
import com.ramos.kuaixiao.db.CustomerWareHouseDB;
import com.ramos.kuaixiao.db.WareHouseDB;
import com.ramos.kuaixiao.entity.Customer;
import com.ramos.kuaixiao.entity.WareHouse;
import com.ramos.kuaixiao.utils.CommonLoading;
import com.ramos.kuaixiao.utils.NetUtils;
import com.ramos.kuaixiao.utils.SharedPreference;
import com.ramos.kuaixiao.utils.StringUtil;
import com.ramos.kuaixiao.utils.ToastUtils;
import com.ramos.kuaixiao.utils.Utils;

import org.apache.http.Header;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;


public class ShopWarehouseActivity extends BaseAllTabActivity implements View.OnClickListener {
    private static String TAG = "ShopWarehouseActivity";
    private TextView title_save;
    private LinearLayout title_reback;
    private LinearLayout ll_unfinished_none;
    private TextView title_text;
    public final static int UPLOAD_SUCCESS = 100;
    public final static int UPLOAD_FAIL = 101;
    private WareAdapter mAdapter;
    private List<WareHouse> wareList = new ArrayList<>();
    ListView whList;
    private CommonLoading loading;
    private Set<String> mUnSelectWare = new HashSet<>();
    CustomerWareHouseDB mCustomerWareHouseDB;
    Customer mCustomer;
    String custmerId;
    String custmerName;
    WareHouseDB mWareHouseDB;

    private RelativeLayout re_home_shop;
    private RelativeLayout re_home_order;
    private RelativeLayout re_home_task;
    private RelativeLayout re_home_my;
    private TextView tv_home_shop;
    private TextView tv_home_order;
    private TextView tv_home_task;
    private TextView tv_home_my;
    private ImageView ib_home_shop;
    private ImageView ib_home_order;
    private ImageView ib_home_task;
    private ImageView ib_home_my;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop_warehouse);
        StatusBarCompat.setStatusBarColor(this, getResources().getColor(R.color.title), false);
        mCustomerWareHouseDB = new CustomerWareHouseDB();
        mWareHouseDB = new WareHouseDB();
        mCustomer = (Customer) getIntent().getExtras().get("customer");
        title_reback = (LinearLayout) findViewById(R.id.title_reback);
        title_reback.setOnClickListener(this);

        title_text = (TextView) findViewById(R.id.title_text);
        title_text.setText("选择仓库");

        title_save = (TextView) findViewById(R.id.title_order);
        title_save.setText("保存");
        title_save.setOnClickListener(this);
        whList = (ListView) findViewById(R.id.whList);
        ll_unfinished_none = (LinearLayout) findViewById(R.id.ll_unfinished_none);
        if (mCustomer != null) {
            if (StringUtil.isEmpty(mCustomer.getHouseId())) {
                custmerId = mCustomer.getId();
            } else {
                custmerId = mCustomer.getHouseId();
            }
            if (StringUtil.isEmpty(mCustomer.getHouseName())) {
                custmerName = mCustomer.getName();
            } else {
                custmerName = mCustomer.getHouseName();
            }
        }
        mAdapter = new WareAdapter(ShopWarehouseActivity.this, wareList);
        whList.setAdapter(mAdapter);
        Log.d(TAG, "onCreate");
        String ws = mCustomerWareHouseDB.findCustomer(custmerId + "", custmerName + "");
        Log.d(TAG, "ws:" + ws);
        //将已选择的仓库过滤出来
        if (ws != null && Utils.strToSet(ws) != null) {
            mUnSelectWare.addAll(Utils.strToSet(ws));
        }
        initLocalDB(SharedPreference.getPreferString("org"));
        initTabView();
    }

    private void initTabView() {
        re_home_shop = (RelativeLayout) findViewById(R.id.re_home_shop);
        re_home_order = (RelativeLayout) findViewById(R.id.re_home_order);
        re_home_task = (RelativeLayout) findViewById(R.id.re_home_task);
        re_home_my = (RelativeLayout) findViewById(R.id.re_home_my);
        re_home_shop.setOnClickListener(this);
        re_home_order.setOnClickListener(this);
        re_home_task.setOnClickListener(this);
        re_home_my.setOnClickListener(this);

        ib_home_shop = ((ImageView) findViewById(R.id.ib_home_shop));
        ib_home_order = ((ImageView) findViewById(R.id.ib_home_order));
        ib_home_task = ((ImageView) findViewById(R.id.ib_home_task));
        ib_home_my = ((ImageView) findViewById(R.id.ib_home_my));

        tv_home_shop = ((TextView) findViewById(R.id.tv_home_shop));
        tv_home_order = ((TextView) findViewById(R.id.tv_home_order));
        tv_home_task = ((TextView) findViewById(R.id.tv_home_task));
        tv_home_my = ((TextView) findViewById(R.id.tv_home_my));

        ib_home_shop.setImageResource(R.drawable.tab_infomation_clk);
        tv_home_shop.setTextColor(getResources().getColor(R.color.title));

        ib_home_order.setImageResource(R.drawable.tab_schedule);
        tv_home_order.setTextColor(getResources().getColor(R.color.bottom_tab_unselected));

        ib_home_task.setImageResource(R.drawable.tab_service);
        tv_home_task.setTextColor(getResources().getColor(R.color.bottom_tab_unselected));

        ib_home_my.setImageResource(R.drawable.tab_contacts);
        tv_home_my.setTextColor(getResources().getColor(R.color.bottom_tab_unselected));

    }


    private void initLocalDB(String org) {
        //wareList = mWareHouseDB.findAllWareHouse(org);
        String houseList = "";
        List<WareHouse> tmpList = new ArrayList<>();
        tmpList.clear();
        wareList = new WareHouseDB().findAllWareHouse(SharedPreference.getPreferString("org"));
        Log.d(TAG, "tbl_WareHouse:" + wareList.size());
        for(WareHouse wareHouse : wareList){
            Log.d(TAG, "wareHouse:" + wareHouse.getName());
        }
        /*List<EmpStoreHouse> list1 = new EmpStoreHouseDB().findAllCustomer();
        if(list1.size() == 0){
            tmpList.addAll(list);
        } else {
            if (list1.size() > 0 && list.size() > 0) {
                for (EmpStoreHouse empStoreHouse : list1) {
                    if (empStoreHouse.getEmpId().equals(SharedPreference.getPreferString("id"))) {
                        houseList = empStoreHouse.getStorehouseList();
                    }
                }
                Log.d(TAG, "houseList:" + houseList);
                if (!StringUtil.isEmpty(houseList)) {
                    String[] list2 = houseList.split("_");
                    if (list2.length > 0) {
                        for (String s : list2) {
                            for (WareHouse wareHouse : list) {
                                if (s.equals(wareHouse.getId())) {
                                    Log.d(TAG, "s:" + s);
                                    tmpList.add(wareHouse);

                                }
                            }
                        }
                    }

                } else {
                    tmpList.addAll(list);
                }
                Log.d(TAG, "tmpList:" + list.size());
            }
        }*/
        Log.d(TAG, "initLocalDB " + tmpList.size());
        if (wareList == null || wareList.size() == 0) {
            //Log.d(TAG, "initLocalDB tmpList == null " + tmpList.size());
            ll_unfinished_none.setVisibility(View.VISIBLE);
            whList.setVisibility(View.GONE);
        } else {
            ll_unfinished_none.setVisibility(View.GONE);
            whList.setVisibility(View.VISIBLE);
            mAdapter = new WareAdapter(ShopWarehouseActivity.this, getWare(wareList, mUnSelectWare));
            whList.setAdapter(mAdapter);
        }
    }

    private void getLocal() {
        //String json  = Utils.getJson(this, "userwarehouse.json");
        sendMessagea(UPLOAD_SUCCESS, App.WARE_RESULT);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_reback:
                finish();
                break;
            case R.id.re_home_shop:
                showMain(1);
                break;
            case R.id.re_home_order:
                showMain(2);
                break;
            case R.id.re_home_task:
                showMain(3);
                break;
            case R.id.re_home_my:
                showMain(4);
                break;
            case R.id.title_order:
                if (wareList == null || wareList.size() == 0) {
                    ToastUtils.show("暂无仓库信息，无法保存");
                } else {
                    if (saveWare() != null && saveWare().size() == wareList.size()) {
                        ToastUtils.show("请至少保留一个仓库！");
                    } else {
                        mCustomer.setWareHouseList(Utils.setToString(saveWare()));
                        mCustomerWareHouseDB.addShop(mCustomer);
                        ToastUtils.show("保存成功");
                        finish();
                    }
                }
                break;
            default:
                break;
        }
    }

    private Set<String> saveWare() {
        List<WareHouse> list = mAdapter.getWareList();
        Set<String> mUnSelectList = new HashSet<>();
        if (list != null && list.size() > 0) {
            for (WareHouse ware : list) {
                if (!ware.isUsed) {
                    mUnSelectList.add(ware.getName());
                }
            }
        }
        return mUnSelectList;
    }

    private void getInventory() {
        try {
            String url = NetUtils.WARE_HORSE;
            String path = url + SharedPreference.getPreferString("dealer") + "&userId=" + SharedPreference.getPreferString("id");
            AsyncHttpClient client = new AsyncHttpClient(); // 创建异步请求的客户端对象
            loading = new CommonLoading(this);
            loading.setLoadText("获取数据中...");
            // 创建请求参数的封装的对象
            client.setTimeout(10000);
            client.get(path, new AsyncHttpResponseHandler() {

                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                    //statusCode:状态码    headers：头信息  responseBody：返回的内容，返回的实体
                    loading.dismiss();
                    //判断状态码
                    try {
                        String result = new String(responseBody, "utf-8");
                        Log.d(TAG, "result " + result);
                        org.json.JSONObject user = new org.json.JSONObject(result);
                        if (user.getInt("status") == 200) {
                            App.WARE_RESULT = result;
                            sendMessagea(UPLOAD_SUCCESS, result);
                        } else {
                            sendMessagea(UPLOAD_FAIL, "fail");
                        }
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        sendMessagea(UPLOAD_FAIL, "fail");
                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers,
                                      byte[] responseBody, Throwable error) {
                    loading.dismiss();
                    sendMessagea(UPLOAD_FAIL, "fail");
                }
            });
        } catch (Exception e) {
            loading.dismiss();
            e.printStackTrace();
        }
    }

    @SuppressLint("HandlerLeak")
    Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case UPLOAD_SUCCESS:
                    Log.d(TAG, "result " + msg.obj.toString());
                    JSONObject jsonObejct = JSONObject.parseObject(msg.obj.toString());
                    JSONObject data = jsonObejct.getJSONObject("data");
                    wareList = JSONArray.parseArray(data.getJSONArray("rows").toString(), WareHouse.class);
                    if (wareList.size() > 0) {
                        mAdapter = new WareAdapter(ShopWarehouseActivity.this, getWare(wareList, mUnSelectWare));
                        whList.setAdapter(mAdapter);
                    }
                    break;
                case UPLOAD_FAIL:
                    Log.d(TAG, "result fail");
                    break;
                default:
                    break;
            }
        }
    };

    private List<WareHouse> getWare(List<WareHouse> wareList, Set<String> mUnSelectWare) {
        List<WareHouse> list;
        for (WareHouse ware : wareList) {
            for (String s : mUnSelectWare) {
                if (ware.getName().equals(s)) {
                    ware.isUsed = false;
                }
            }
        }
        list = wareList;
        return list;
    }

    private void sendMessagea(int iWhat, Object obj) {
        Message msg = Message.obtain();
        msg.what = iWhat;
        msg.obj = obj;
        mHandler.sendMessage(msg);
    }
}


